import {v1 as uuidv1} from 'uuid'

/**
 *
 * @param url       websocket的连接地址
 * @param callbacks 回调函数
 *  - beforeClose(): 关闭之前的回调函数，返回false可终止关闭
 *  - afterClose(): 关闭之后的回调函数
 *
 *  - onopen(): 打开socket连接后的回调函数
 *  - onmessage(data, msg): 接收到服务器发来的消息时的回调函数。
 *
 * @return 返回当前对象
 * @constructor
 */
export default function Socket(url, callbacks) {

    this._id = uuidv1()

    this.socket = null

    /**
     * 初始化
     */
    this.init = function () {
        if (this.is()) {
            this.close()
        }


        this.socket = new WebSocket(url)

        /**
         * 打开websocket会话连接
         */
        this.socket.onopen = () => {
            if (callbacks.onopen) {
                callbacks.onopen.call(this)
            }
        }

        /**
         * 接收服务器发来的消息
         * @param e
         */
        this.socket.onmessage = msg => {
            if (callbacks.onmessage) {
                callbacks.onmessage.call(this, msg.data, msg)
            }
        }

        return this
    }

    /**
     * 关闭socket连接
     */
    this.close = function () {
        if (callbacks.beforeClose) {
            const b = callbacks.beforeClose.call(this)
            if (b === false) {
                return
            }
        }

        if (this.is()) {
            this.socket.close()
            this.socket = null

            if (callbacks.afterClose) {
                callbacks.afterClose.call(this)
            }
        }
    }

    /**
     * 判断是否有socket
     * @returns {boolean}
     */
    this.is = function () {
        return this.socket !== null
    }

    /**
     * 发送消息给服务器
     * @param data 要发送的消息，格式必须是JSON对象
     */
    this.send = function (data) {
        if (!this.is()) {
            return this
        }

        this.socket.send(JSON.stringify(data))
        return this
    }

    return this
}
